package java114.jdbc;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
    //1.创建数据源
    public static DataSource dataSource = null;
    //连接字符串
    public static final String URL = "jdbc:mysql://127.0.0.1:3306/java114?characterEncoding=utf8&allowPublicKeyRetrieval=true&useSSL=false";
    //用户名
    public static final String USER = "root";
    //密码
    public static final String PASSWORD = "123456";

    static {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setURL(URL);
        mysqlDataSource.setUser(USER);
        mysqlDataSource.setPassword(PASSWORD);
        dataSource = mysqlDataSource;
    }
    //私有化防止new这个对象
    private DBUtil(){}
    //获取数据库连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    //关闭连接

    public static void close(ResultSet resultSet, Statement statement, Connection connection){
        if(resultSet != null){
            try{
                resultSet.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }

        if(statement != null){
            try{
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(connection != null){
            try{
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }


}
